package com.mew.chess.core.game.pokdeng.game.task;

import com.mew.chess.core.common.handler.ChessPushMessageUtil;
import com.mew.chess.core.common.provide.GameFeignService;
import com.mew.chess.core.common.utils.ChessGameUtil;
import com.mew.chess.core.game.pokdeng.game.PokDengGameManager;
import com.mew.chess.core.game.pokdeng.game.PokDengSeatManager;
import com.mew.chess.core.game.pokdeng.game.PokDengTableManager;
import com.mew.chess.core.game.pokdeng.game.common.PokDengConstantValue;
import com.mew.chess.core.game.pokdeng.game.common.PokDengLinkType;
import com.mew.chess.core.game.pokdeng.game.common.PokDengPushCMDMapType;
import com.mew.chess.core.game.pokdeng.game.message.PaymentMessage;
import com.mew.chess.core.game.pokdeng.game.message.PushPaymentMessage;
import com.mew.chess.core.game.pokdeng.game.message.UserMessage;
import com.mew.common.dc.redis.GameRoomRedisService;
import com.mew.common.enm.UserType;
import com.mew.common.entity.config.Room;
import com.mew.common.entity.game.RoomProfile;
import com.mew.common.rest.game.BetAfterRequest;
import com.zebra.common.concurrent.ZebraExecutorManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dylin
 * @create 2021/4/29
 */
@Component
@Slf4j
public class PokDengPaymentTask {
    @Autowired
    private GameRoomRedisService gameRoomRedisService;
    @Autowired
    private GameFeignService feignService;
    /**
     * 赔付
     */
    public void payment(int roomId,int tableId){
        PokDengGameManager gameManager = PokDengGameManager.getInstance();
        PokDengTableManager table = gameManager.getController(roomId).getTableManager(tableId);
        Room room = gameRoomRedisService.getRedisRoom(gameManager.getGameId(), roomId);
        for (PokDengSeatManager seat : table.getSeatMap().values()) {
            if(seat.getUser()!=null&&seat.getUser().getBet()>0){
                if(seat.getUser().getUserType()==UserType.Robot.code()){
                    seat.getUser().setPlayTimes(seat.getUser().getPlayTimes()-1);
                }
                payment(table.getBanker().getUser(),seat.getUser(),room);
            }
        }
        persistenceData(table,room,roomId);
        sendPaymentMsg(table);
        pushLog(table);
        table.changeLink(PokDengLinkType.Payment.code(), PokDengConstantValue.PAYMENT_TIME);
    }
    private void payment(UserMessage banker, UserMessage user,Room room){
        if(user.getCardVal()>banker.getCardVal()){
            userWin(banker,user,room);
        }else if(user.getCardVal()<banker.getCardVal()){
            userLose(banker,user,room);
        }else{
            equal(user);
        }
        user.getGameSession().updateGoldNumber(user.getPayment());
    }
    private void userWin(UserMessage banker, UserMessage user,Room room){
        long payment = user.getBet()*user.getCardRate();
        int tax = 0;
        user.setPayment(user.getBet() + payment - tax);
        user.setTax(tax);
        banker.setBet(user.getBet()*user.getCardRate());
    }
    private void userLose(UserMessage banker, UserMessage user ,Room room){
        banker.setPayment(user.getBet()*banker.getCardRate());
        user.setPayment(-1*user.getBet()*(banker.getCardRate()-1));
        user.setBet(user.getBet()*banker.getCardRate());
    }
    private void equal(UserMessage user){
        user.setPayment(user.getBet());
    }
    private void persistenceData(PokDengTableManager table, Room room, int roomId){
        RoomProfile roomProfile = gameRoomRedisService.getRoomProfile(roomId);
        List<BetAfterRequest> list=new ArrayList<>(10);
        for (PokDengSeatManager seat : table.getSeatMap().values()) {
            if(seat.getUser()!=null&&seat.getUser().getBet()>0&&seat.getUser().getUserType()!=UserType.Robot.code()){
                list.add(builPlayRecord(room,roomProfile,table.getBanker().getUser(),seat.getUser(),PokDengGameManager.getInstance().getGameId(),roomId,table.getTableId(),seat.getSeatNo()));
            }
        }
        ZebraExecutorManager.getInstance().getDefaultExecutor().execute(() -> {
            feignService.chessBetAfter(list);
        });
    }
    private BetAfterRequest builPlayRecord(Room room, RoomProfile roomProfile,UserMessage banker,UserMessage userMessage, int gameId, int roomId, int tableId, int seatNo){
        BetAfterRequest request = BetAfterRequest.builder()
                .uid(userMessage.getUserId())
                .relateInoutId(userMessage.getGameSession().getInoutId())
                .gameId(gameId)
                .roomId(roomId)
                .tableId(tableId)
                .seatNo(seatNo)
                .bet(userMessage.getBet())
                .roomRecord(1)
                .payment(userMessage.getPayment()<0?0:userMessage.getPayment())
                .betTimes((int)(userMessage.getPayment() / userMessage.getBet()))
                .iconResult(banker.getCards().toString()+"-"+userMessage.getCards().toString())
/*                .bloodBalance(room.getStratBloodBalance())
                .bloodValue(roomProfile.getBloodValue())*/
                .betArray(String.valueOf(userMessage.getBet()))
                .paymentArray(String.valueOf(userMessage.getPayment()))
                .tax(userMessage.getTax())
                .build();

        return request;
    }
    private void sendPaymentMsg(PokDengTableManager table){
        UserMessage banker=table.getBanker().getUser();
        PushPaymentMessage pushPaymentMessage=new PushPaymentMessage();
        pushPaymentMessage.setBankerPayment(banker.getPayment()-banker.getBet());
        List<PaymentMessage> payments=new ArrayList<>();
        for (PokDengSeatManager seat : table.getSeatMap().values()) {
            if(seat.getUser()!=null){
                payments.add(PaymentMessage.buildPayment(seat));
            }
        }
        pushPaymentMessage.setPayments(payments);
        ChessPushMessageUtil.broadcastMessage(table.getOnlineUser().values(), PokDengPushCMDMapType.PaymentMessage.code(),pushPaymentMessage);
    }

    private void pushLog(PokDengTableManager tableManager){
        UserMessage bank=tableManager.getBanker().getUser();
        tableManager.getSeatMap().values().stream().filter(seat -> seat.getUser()!=null&&seat.getUser().getUserType()!=UserType.Robot.code()&&seat.getUser().getBet()>0).forEach(seat->{
            UserMessage u=seat.getUser();
            List<int[]> cards=new ArrayList<>();
            cards.add(bank.getCards().stream().mapToInt(Integer::intValue).toArray());
            cards.add(u.getCards().stream().mapToInt(Integer::intValue).toArray());
            ChessGameUtil.ccLog(0,u.getGameSession(),u.getBet(),u.getPayment(),cards);
        });
    }
}
